package cn.kgcnews.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.kgcnews.listener.UserActiveListener;
import cn.kgcnews.pojo.User;
import cn.kgcnews.service.UserService;
import cn.kgcnews.service.impl.UserServiceImpl;

public class UserServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
this.doPost(request, response);
	}

	private void doReg(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		String email = request.getParameter("email");
		String userType=request.getParameter("userType");
		User user = null;
		if(userType!=null&&!userType.equals("")){
			
		user = new User();
		user.setUserName(userName);
		user.setUserPass(userPwd);
		user.setType(Integer.valueOf(userType));
		}else{
			user = new User(userName, userPwd, 1, email);
		}
		// 将数据封装为User对象
		
		// 添加业务逻辑层的引用
		UserService userService = new UserServiceImpl();
		int result = userService.registerUser(user);
		if (result == 1) {
			// 注册成功
			out.println("<script>alert('恭喜您，注册成功，请前往登录页面');location.href='index.jsp';</script>");
		} else if (result == 0) {
			// 用户名被占用
			out.println("<script>alert('注册失败，用户名被占用，请前往首页');location.href='index.jsp';</script>");
		} else {
			// 注册失败
			out.println("<script>alert('注册失败，请前往首页');location.href='index.jsp';</script>");
		}
		out.flush();
		out.close();
	}
	
	private void doOut(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//处理用户的注销请求
		HttpSession session=request.getSession();
		//设置会话失效
		//session.invalidate();
		session.removeAttribute("listener");
		//创建cookie
		Cookie cookie = new Cookie("code", null);
		//设置有效期
		cookie.setMaxAge(0);
		//有效路径
		cookie.setPath("/");
		//由服务器向客户端写入cookie
		response.addCookie(cookie);
		//重定向到首页
		response.sendRedirect("index.jsp");
	}
	private void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		UserService userService=new UserServiceImpl();
		//验证用户名和密码
		User user=userService.login(userName, userPwd);
		//判断用户名和密码
		if (user!=null) {
			if(user.getType()==0){
			    //管理员
			    //保存用户的登录状态
				HttpSession session=request.getSession();
			    session.setAttribute("loginUser", user);
			    //设置会话的有效期(单位是秒)
			    session.setMaxInactiveInterval(600);
			    response.sendRedirect("manage/index.jsp");
			}else if(user.getType()==1){
				HttpSession session =request.getSession();
			    UserActiveListener listener= new UserActiveListener();
			    session.setAttribute("listener", listener);
			    //普通用户
				String code=user.getUserName()+"&"+user.getUserPass();
				//将cookie的内容设置为utf-8的编码方式
				code=URLEncoder.encode(code, "UTF-8");
			    //创建cookie
			    Cookie cookie=new Cookie("code",code);
			    //保存十天
			    cookie.setMaxAge(10*24*3600);
			    //有效路径
			    cookie.setPath("/");
			    //由服务器向客户端写入cookie
			    response.addCookie(cookie);
			    response.sendRedirect("index.jsp");
			}

		} else {
			//用户名和密码不正确,出现弹框提示信息，之后页面跳转到前台首页
			out.println("<script>alert('用户名和密码不正确');location.href='index.jsp';</script>");
		}
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");
		// 接收用户的请求数据
		request.setCharacterEncoding("UTF-8");
		// 优先接受处理的参数
		String action = request.getParameter("action");
		if (action != null && !action.equals("")) {
			if (action.equals("reg")) {
				this.doReg(request, response);
			}else if(action.equals("log")){
				this.doLogin(request, response);
			}else if(action.equals("out")){
				this.doOut(request, response);
			}else{
				
				out.println("<script>location.href='index.jsp';</script>");
			}
		}
		

	}


	public void init() throws ServletException {
		System.out.println("初始化的步骤1");
	}

	/*@Override
	public void init(ServletConfig config) throws ServletException {
		System.out.println("初始化的步骤2");
	}*/

}
